const Promise = require('bluebird');
const adminV1 = require('./v1/admin');
const frontV1 = require('./v1/front');
const sectionV1 = require('./v1/section');

let apis = {

    /**
     * 如何使用
     */
    '/how_to_use': {
        handler: frontV1.howToUse
    },

    /**
     * 登录
     */
    '/login': {
        handler: frontV1.login,
        render: 'front/views/login'
    },

    /**
     * 忘记密码
     */
    '/forgot': {
        handler: frontV1.forgot,
        render: 'front/views/forgot'
    },

    /**
     * 注册
     */
    '/register': {
        handler: frontV1.register,
        render: 'front/views/register'
    },

    /**
     * 首页
     */
    '/': {
        handler: frontV1.index,
        render: 'front/views/index'
    },

    /**
     * 品牌
     */
    '/pinpai': {
        handler: frontV1.pinpai,
        render: 'front/views/pinpai'
    },

    /**
     * 跑单
     */
    '/sales': {
        handler: frontV1.sales,
        render: 'front/views/sales'
    },

    /**
     * 神单
     */
    '/shendan': {
        handler: frontV1.shendan,
        render: 'front/views/shendan'
    },

    /**
     * 详情页
     */
    '/detail': {
        handler: frontV1.detail,
        render: 'front/views/detail'
    },

    /**
     * 用户中心
     */
    '/user_center': {
        permission: true,
        handler: frontV1.userCenter,
        render: 'front/views/user_center'
    },

    /**
     * 编辑用户信息
     */
    '/user_edit': {
        permission: true,
        handler: frontV1.userEdit,
        render: 'front/views/user_edit'
    },

    /**
     * 申请提现
     */
    '/withdraw_apply': {
        permission: true,
        handler: frontV1.withdrawApply,
        render: 'front/views/withdraw_apply'
    },

    /**
     * 设置提现账号
     */
    '/bank_edit': {
        permission: true,
        handler: frontV1.bankEdit,
        render: 'front/views/bank_edit'
    },

    /**
     * 资金流水
     */
    '/finances': {
        permission: true,
        handler: frontV1.finances,
        render: 'front/views/finances'
    },
    '/user_finances': {
        permission: true,
        handler: frontV1.userFinances,
        render: 'front/views/finances'
    },

    /**
     * 提现记录
     */
    '/withdraws': {
        permission: true,
        handler: frontV1.withdraws,
        render: 'front/views/withdraws'
    },
    '/user_withdraws': {
        permission: true,
        handler: frontV1.userWithdraws,
        render: 'front/views/withdraws'
    },

    /**
     * 结算管理
     */
    '/partner_settles': {
        permission: true,
        handler: frontV1.partnerSettles,
        render: 'front/views/partner_settles'
    },

    '/partner_users': {
        permission: true,
        handler: frontV1.partnerUsers,
        render: 'front/views/partner_users'
    },

    '/partner_withdraws': {
        permission: true,
        handler: frontV1.partnerWithdraws,
        render: 'front/views/partner_withdraws'
    },

    /**
     * 我的粉丝
     */
    '/fans_list': {
        permission: true,
        handler: frontV1.fansList,
        render: 'front/views/fans_list'
    },

    /**
     * 代理管理
     */
    '/partner_agency': {
        permission: true,
        handler: frontV1.partnerAgency,
        render: 'front/views/partner_agency'
    },

    /**
     * 合伙人订单
     */
    '/partner_orders': {
        permission: true,
        handler: frontV1.partnerOrders,
        render: 'front/views/partner_orders'
    },

    /**
     * 粉丝订单
     */
    '/fans_orders': {
        permission: true,
        handler: frontV1.fansOrders,
        render: 'front/views/fans_orders'
    },

    /**
     * 我的订单
     */
    '/my_orders': {
        permission: true,
        handler: frontV1.myOrders,
        render: 'front/views/my_orders'
    },

    /**
     * 浏览记录
     */
    '/goodses_views': {
        permission: true,
        handler: frontV1.goodsesViews,
        render: 'front/views/goodses_views'
    },

    /**
     * 搜索记录
     */
    '/goodses_searchs': {
        permission: true,
        handler: frontV1.goodsesSearchs,
        render: 'front/views/goodses_searchs'
    },

    /**
     * 建议反馈
     */
    '/suggestions': {
        handler: frontV1.suggestions,
        render: 'front/views/suggestions'
    },

    /**
     * 我的客服
     */
    '/customers': {
        handler: frontV1.customers,
        render: 'front/views/customers'
    },

    /**
     * 文章详情
     */
    '/article': {
        handler: frontV1.article,
        render: 'front/views/article'
    },

    /**
     * 文章列表
     */
    '/articles': {
        handler: frontV1.articles,
        render: 'front/views/articles'
    },

    /**
     * 最近浏览
     */
    '/last_visitors': {
        handler: frontV1.lastVisitors,
        render: 'front/views/last_visitors'
    },

    /**
     * 搜索商品列表页
     */
    '/section/search': {
        handler: sectionV1.search,
        render: 'front/views/secgoodses'
    },

    /**
     * 列表页
     */
    '/section/browse': {
        handler: sectionV1.browse,
        render: 'front/views/secgoodses'
    },

    /**
     * 浏览记录
     */
    '/section/browse_views': {
        handler: sectionV1.browseViews,
        render: 'front/views/secgoodses'
    },

    /**
     * 搜索记录
     */
    '/section/browse_search': {
        handler: sectionV1.browseSearch,
        render: 'front/views/secgoodses'
    },

    /**
     * 店铺优惠券
     */
    '/section/store_goodses': {
        handler: sectionV1.storeGoodses,
        render: 'front/views/secgoodses'
    },

    /**
     * 领取优惠券
     */
    '/section/popcoupon': {
        handler: sectionV1.popcoupon,
        render: 'front/views/popcoupon'
    },

    /**
     * 店铺优惠券
     */
    '/section/store_coupons': {
        handler: sectionV1.storeCoupons,
        render: 'front/views/seccoupons'
    },

    /**
     * 商品优惠券
     */
    '/section/goods_coupons': {
        handler: sectionV1.goodsCoupons,
        render: 'front/views/seccoupons'
    },

    /**
     * 价格走势
     */
    '/section/price_trend': {
        handler: sectionV1.priceTrend,
        render: 'front/views/pricetrend'
    },

    /**
     * 阿里妈妈搜索
     */
    '/section/alimama_search': {
        handler: sectionV1.alimamaSearch,
        render: 'front/views/secalimama'
    },

    /**
     * 忘记密码
     */
    '/admin_forgot': {
        handler: adminV1.forgot,
        render: 'admin/views/forgot'
    },

    /**
     * 后台管理
     */
    '/admin': {
        handler: adminV1.admin,
        render: 'admin/views/admin'
    },
}

/**
 * 请求转发，权限控制，数据处理
 */
let attributes = [`id`, `openid`, `tel`, `nickname`, `username`, `image`, `banner`, `join_qrcode`, `join_qrcode_mediaid`, `return_qrcode`, `return_qrcode_mediaid`,
    `level`, `until`, `role`, `domain`, `domain_pid`, `view_level`, `partner_id`, `agency_id`, `inviter_id`, `order_return_scale`, `order_return_limit`, `first_return_scale`, `first_return_limit`,
    `return_quick`, `first_quick`, `agency_scale`, 'inviter_agency_scale', 'inviter_scale', `order_count`, `finish_count`, `sham_count`, `amount`, `frozen`, `point`, `tao_user`, `pid`, `alimamaId`, `mediumId`, `adPositionId`, `we_id`, `qq_id`,
    `notifyAllOrder`, `notifyMyOrder`, 'subscribe', 'sex', `status`, `created_at`];
module.exports = function (storage, config) {
    return function (req, res, next) {
        let path = req.override_path || req.path, pathLen = path.length;

        if (/^\/(\d)+$/.test(path)) {
            let urlId = path.substr(1);
            return storage.models.ShortUrls.findOne({where: {id: urlId}}).then(function (shortUrl) {
                if (shortUrl) {
                    return res.redirect(shortUrl.url);
                }
            });
        }

        if (pathLen > 1 && path.lastIndexOf('/') == pathLen - 1) {
            path = req.path.substr(0, pathLen - 1);
        }

        let api = apis[path];
        if (api) {
            let {handler, permission, render} = api;
            let user_id = req.session.user_id;
            //权限处理
            let host = req.hostname;
            return Promise.resolve().then(function () {
                if (user_id) {
                    return storage.models.Users.findOne({where: {id: user_id}, attributes: attributes});
                }
                let openid = req.query.openid;
                if(openid){
                    return storage.models.Users.findOne({where: {openid: openid}, attributes: attributes}).then((user)=>{
                      if(user){
                        user_id = user.id;
                        req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 30 * 12;
                        req.session.user_id = user.id;
                        req.session.touch();
                      }
                      return user;
                    });
                }
                return null;
            }).then(function (user) {
                /**
                 * 微信访问, 自动登录
                 */
                if (!user) {
                    let useragent = req.headers['user-agent'] ? req.headers['user-agent'].toLowerCase() : '';
                    if (useragent.indexOf('micromessenger') != -1) {
                        let code = req.query.code;
                        if (!code) {
                            if (config.domainMap[host]) {
                                let redirectUrl = config.domain + '/get-weixin-code.html?appid=' + config.wechat.shop_web_appid + '&scope=snsapi_base&state=123&redirect_uri=' + encodeURIComponent('http://' + host + (req.originalUrl || req.url));

                                console.log('redirectUrl', redirectUrl);
                                return {redirect: redirectUrl};
                            }
                            return {redirect: storage.wechatInstance.shopWebOauth.getAuthorizeURL('http://' + (host == 'localhost' ? config.localhost : host) + (req.originalUrl || req.url), '123', 'snsapi_userinfo')};
                        }

                        return new Promise(function (resolve) {
                            storage.wechatInstance.shopWebOauth.getAccessToken(code, function (err, result) {
                                if (err || !result || !result.data) {
                                    if (err) {
                                        console.error('\n', err.stack || err.message);
                                    }
                                    console.log(result);
                                    return resolve({success: false, message: '获取数据错误'});
                                }
                                let {openid} = result.data;
                                if (!openid) {
                                    return resolve({success: false, error: result});
                                }
                                let inviter_id = req.query.inviter_id;
                                return storage.wechatInstance.getUserByOauth(result.data, inviter_id ? {inviter_id: inviter_id} : {}).then(function (result) {
                                    if (result.success) {
                                        user = result.data;
                                        if (user) {
                                            user_id = user.id;
                                        }
                                        req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 30 * 12;
                                        req.session.user_id = user.id;
                                        req.session.touch();
                                    }
                                    return resolve(result);
                                });
                            });
                        }).then(function (result) {
                            if (permission && !user_id) {
                                res.redirect('/login');
                                return;
                            }
                            return handler({
                                req: req,
                                res: res,
                                body: req.body,
                                query: req.query,
                                session: req.session,
                                user_id: user_id,
                                user: user
                            }, storage);
                        });
                    } else {
                        let inviter_id = req.query && req.query.inviter_id;
                        if (inviter_id) {
                            req.session.inviter_id = inviter_id;
                            req.session.touch();
                        }
                    }
                }

                if (permission && !user_id) {
                    res.redirect('/login');
                    return;
                }

                return handler({
                    req: req,
                    res: res,
                    body: req.body,
                    query: req.query,
                    session: req.session,
                    user_id: user_id,
                    user: user
                }, storage);
            }).then(function (response) {
                if (response) {
                    if (response.redirect) {
                        return res.redirect(response.redirect);
                    }
                    return res.render(render, response);
                }
            }, function (err) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                }
                return res.json({success: false, code: 500, message: err.message || '请求异常'});
            });
        } else {
            next();
        }
    };
};
